<?php

class UserController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		$data['error'] = 'none';
		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$identity=new UserIdentity($_POST['LoginForm']['email'],$_POST['LoginForm']['password']);
			if($identity->authenticate()) {
			    Yii::app()->user->login($identity);
				$this->redirect(Yii::app()->homeUrl);
			} else {
				$data['error'] = $identity->errorCode;
			}
		} 
		// display the login form

		$data['questions'] = Question::model()->findAll();
		$data['variants'] = array();
		foreach ($data['questions'] as $question) {
			$data['variants'][$question->id] = Variant::model()->findAllByAttributes(array('q_id' => $question->id));
		}

		$this->render('login', $data);
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionRegister() {
		$model = new User;

		if(isset($_POST['user'])) {
			$user = $_POST['user'];
			$user['bday'] = $user['day'].'-'.$user['month'].'-'.$user['year'];

			$model->attributes = $user;

			
			$model->name = $user['name'];
			$model->password = md5($user['password']);
			$model->surname = $user['surname'];
			if(isset($user['fname']))
				$model->fname = $user['fname'];
			else
				$model->fname = ' ';
			//$model->bday = $user['day'].'-'.$user['month'].'-'.$user['year'];
			$model->sex = $user['sex'];
			$model->tel1 = $user['tel1'];
			$model->tel2 = $user['tel2'];
			$model->tel3 = $user['tel3'];
			if(isset($user['subscribed']))
				$model->subscribed = $user['subscribed'];

			if($model->save()) {
				$this->redirect(Yii::app()->homeUrl);
			}
		}
	}

}